package com.fuego.creditsystemcommodity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fuego.creditsystemcommodity.mapper.ActivityInfoMapper;
import com.fuego.creditsystemcommodity.service.IActivityInfoService;
import jakarta.annotation.Resource;
import org.example.dto.Result;
import org.example.entity.ActivityInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static org.example.utils.RedisConstants.ACTIVITY_INFO_STOCK_KEY;


@Service
public class ActivityInfoServiceImpl extends ServiceImpl<ActivityInfoMapper, ActivityInfo> implements IActivityInfoService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ActivityInfoMapper activityInfoMapper;

    @Override
    public Result queryActivityInfoById(Long activityId) {
        // 查询数据库
        LambdaQueryWrapper<ActivityInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ActivityInfo::getActivityId, activityId);
        List<ActivityInfo> activityInfos = activityInfoMapper.selectList(wrapper);

        // 如果数据为空，返回错误
        if (activityInfos == null || activityInfos.isEmpty()) {
            return Result.fail("未找到活动信息");
        }

        // 缓存到 Redis，设置 1 小时过期时间
        for (ActivityInfo activityInfo : activityInfos) {
            String key = ACTIVITY_INFO_STOCK_KEY+ activityInfo.getActivityId() + ":" + activityInfo.getActivityStartTime();
            stringRedisTemplate.opsForValue().set(key, activityInfo.getStock().toString(), 1, TimeUnit.HOURS);
        }

        // 返回结果
        return Result.ok(activityInfos);
    }
}
